#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import time
from optparse import OptionParser

from htlib import *
from cluster import ClusterConfig

def main(home_dir, cluster_name, test):
    nfs_mkdirs('%s/share_dir' % home_dir)

    cluster = ClusterConfig(home_dir, cluster_name)
    clients = ','.join(cluster.get_clients())

    sdir = cluster.conf['cluster_share_dir']

    os.system("mkdir -p %s" % sdir)  #make sure the dir exist

    os.system("find %s -maxdepth 1 -type d -name 'tc*' -exec tar cjvf {}-%d.tar.bz2 {} \;" % (sdir, int(time.time())))
    os.system("mv %s/*.bz2 %s/share_dir" % (sdir, home_dir))
    os.system('rm -rf %s/tc*' % sdir)
    os.system('rm %s/TestEnv.lock' % sdir)
    os.system('pdsh -f %d -w %s "pkill -9 -f TestIO"' % (options.pdsh, clients))
    os.system('pdsh -f %d -w %s "pkill -9 -f hdfstestcase"' % (options.pdsh, clients))
    if options.self_test:
        os.system('pdsh -f %d -w %s "python %s/hadoop-test/script/hdfstestcase.py -H %s -c %s -t %d -T"' % ( \
                options.pdsh, clients, home_dir, home_dir, cluster_name, test, options.minor))
    else:
        os.system('pdsh -f %d -w %s "python %s/hadoop-test/script/hdfstestcase.py -H %s -c %s -t %d -r %d -i %s"' % ( \
            options.pdsh, clients, home_dir, home_dir, cluster_name, test, options.wr_ratio, options.interface))


if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option("-H", "--htest",    dest="home_dir",     type='string', help="htest home dir", default="/application/testhdp")
    parser.add_option("-c", "--cluster",  dest="cluster_name", type='string', help="cluster name",   default="cluster1")
    parser.add_option("-t", "--test",     dest="test",         type='int',    help="run which test", default=0)
    parser.add_option("-f", "--pdsh",      dest="pdsh",        type='int',    help="pdsh -f option", default=256)
    parser.add_option("-r", "--wr_ratio",  dest="wr_ratio",    type='int',    help="w/r time radio",    default=4)
    parser.add_option("-T", "--selftest",  dest="self_test",   action="store_true", default=False)
    parser.add_option("-i", "--interface", dest="interface",   type='string', help="network interface", default="eth0")
    (options, args) = parser.parse_args() 
    main(options.home_dir, options.cluster_name, options.test)
